package com.fly.estore.framework.session.support;

import com.fly.estore.framework.session.AccountSession;
import com.fly.estore.framework.session.SessionManager;
import com.fly.estore.framework.util.CookieUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by Fly on 2016/3/30.
 */
public class SessionArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    SessionManager sessionManager;

    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.getParameterAnnotation(SessionInfo.class) != null;
    }

    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);

        String sessionId = CookieUtil.readCookie(request, CookieUtil.ACCOUNT_COOKIE);
        if (StringUtils.isNotBlank(sessionId)){
            AccountSession accountSession =  sessionManager.getAccountSession(request, sessionId);
            return accountSession;
        }

        return null;
    }
}
